package com.newear.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.support.v7.app.AppCompatActivity;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.newear.MyApplication;
import com.newear.R;
import com.newear.bean.ReportInfo;
import com.newear.constant.DataType;
import com.newear.constant.RequireParams;
import com.newear.happyCustomView.CustomCircleProgressBar;
import com.newear.happyDialog.FaceTougueDialog;
import com.newear.happyDialog.HealthPlanDialog;
import com.newear.happyDialog.HealthStateDialog;
import com.newear.message.MessageDispatcher;
import com.newear.message.MessageType;
import com.newear.util.MyLogger;
import com.newear.util.MyMediaPlayer;
import com.newear.util.ProgressDialogUtil;
import com.newear.util.T;
import com.newear.util.Validator;
import com.newear.util.ZXingUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HappyReportActivity extends AppCompatActivity {
    private static final String TAG = "HappyReportActivity";
    
    private LinearLayout mlLReport_color_container;
    private LinearLayout mlL_health_state_container;
    private Context mContext;
    private ArrayList mColorList;
    private Map<String, Object> mHealthMap;
    //关闭页面
    private ImageView img_report_close;
    private TextView tv_report_check_time;
    private ImageView img_report_share;

    //这个是健康值包裹的View,颜色需要根据得到的分数,去不同的值显示
    private RelativeLayout rl_health_container_bg;
    private TextView tv_report_health_result;

    //面色值
    private Button mFaceButton;
    private CustomCircleProgressBar mFaceLeftProgressBar;
    private CustomCircleProgressBar mFaceMiddleProgressBar;
    private CustomCircleProgressBar mFaceRightProgressBar;
    private Button btn_face_review;

    //舌色值
    private Button mTongueButton;
    private CustomCircleProgressBar mTongueLeftProgressBar;
    private CustomCircleProgressBar mTongueMiddleProgressBar;
    private CustomCircleProgressBar mTongueRightProgressBar;
    private Button btn_tongue_review;
    private MediaPlayer mediaPlayer;
    //健康方案
    private Button btn_health_plan;
    //数据
    private ReportInfo mReportInfo;
    private int reportId;
    private String key;
    private MyHandler myHandler;
    private ProgressDialog mProgressDialog; //网络请求时用的进度条

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.happy_report_layout);
        init();
        findViews();
        setListeners();
        if (reportId <= 0) {
            resolveBackInfo(mReportInfo);
        }
    }

    private void init(){
        this.mContext = this;
        this.key = this.hashCode() + "";
        myHandler = new MyHandler(this);
        mProgressDialog = ProgressDialogUtil.getProgressDialog(mContext);
        mediaPlayer = MyMediaPlayer.getInstance().playing(this, "raw/report.mp3");
        reportId = getIntent().getIntExtra("id", 0);
        if (reportId <= 0) {
            mReportInfo = MyApplication.sReportInfo;
            //下面表示不是从查看报告点击进入的,直接点击报告进入的
            if (mReportInfo == null){
                mReportInfo = MyApplication.sReportInfo;
            }
        } else {
            getReport(reportId);
        }
        //配置方格的颜色
        initFillColor();
        //配置健康状态的图片，文字
        initHealthBtn();
    }

    /**
     * 得到报告
     */
    private void getReport(int reportId) {
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(RequireParams.DATA_TYPE, DataType.GET_REPORT_BY_ID);
        param.put(RequireParams.MAP_KEY, this.key + DataType.GET_REPORT_BY_ID);
        param.put(RequireParams.ID, reportId);
        param.put(RequireParams.CALL_BACK_HANDLER, myHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
        }
        mediaPlayer = null;
    }

    private void findViews(){
        img_report_close = (ImageView) findViewById(R.id.img_report_close);
        tv_report_check_time = (TextView) findViewById(R.id.tv_report_check_time);
        //二维码分享图片
        img_report_share = (ImageView) findViewById(R.id.img_report_share);
        rl_health_container_bg = (RelativeLayout) findViewById(R.id.rl_health_container_bg);
        tv_report_health_result = (TextView) findViewById(R.id.tv_report_health_result);

        mlLReport_color_container = (LinearLayout) findViewById(R.id.lL_report_color_container);

        mlL_health_state_container = (LinearLayout) findViewById(R.id.lL_health_state_container);

        //面色值相关
        mFaceButton = (Button) findViewById(R.id.btn_face_review);
        mFaceLeftProgressBar = (CustomCircleProgressBar) findViewById(R.id.face_progressbar_left);
        mFaceMiddleProgressBar = (CustomCircleProgressBar) findViewById(R.id.face_progressbar_middle);
        mFaceRightProgressBar = (CustomCircleProgressBar) findViewById(R.id.face_progressbar_right);

        btn_face_review = (Button) findViewById(R.id.btn_face_review);

        //舌色值相关
        mTongueButton = (Button) findViewById(R.id.btn_tongue_review);
        mTongueLeftProgressBar = (CustomCircleProgressBar) findViewById(R.id.tongue_progressbar_left);
        mTongueMiddleProgressBar = (CustomCircleProgressBar) findViewById(R.id.tongue_progressbar_middle);
        mTongueRightProgressBar = (CustomCircleProgressBar) findViewById(R.id.tongue_progressbar_right);

        btn_tongue_review = (Button) findViewById(R.id.btn_tongue_review);

        btn_health_plan = (Button) findViewById(R.id.btn_health_plan);
    }

    private void setListeners(){
        img_report_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //面色查看分析
        btn_face_review.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FaceTougueDialog mDialog = new FaceTougueDialog(mContext,R.style.dialog, "面色分析", FaceTougueDialog.Type.FACE);
                mDialog.setFaceResult(mReportInfo.faceResult);
                mDialog.show();
            }
        });

        //舌色查看分析
        btn_tongue_review.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FaceTougueDialog mDialog = new FaceTougueDialog(mContext,R.style.dialog, "舌色分析", FaceTougueDialog.Type.TONGUE);
                mDialog.setTongueResult(mReportInfo.tongueResult);
                mDialog.show();
            }
        });

        //查看健康原则
        btn_health_plan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HealthPlanDialog planDialog = new HealthPlanDialog(mContext, R.style.dialog);
                planDialog.setReportInfo(mReportInfo);
                planDialog.show();
                //T.longToast(mContext, "该功能暂未实现！");
            }
        });

    }

    private void initFillColor(){
        ArrayList colorList = new ArrayList();
        colorList.add(mContext.getResources().getColor(R.color.happy_color_fill_0));
        colorList.add(mContext.getResources().getColor(R.color.happy_color_fill_1));
        colorList.add(mContext.getResources().getColor(R.color.happy_color_fill_2));
        colorList.add(mContext.getResources().getColor(R.color.happy_color_fill_3));
        colorList.add(mContext.getResources().getColor(R.color.happy_color_fill_4));
        colorList.add(mContext.getResources().getColor(R.color.happy_color_fill_5));
        colorList.add(mContext.getResources().getColor(R.color.happy_color_fill_6));
        colorList.add(mContext.getResources().getColor(R.color.happy_color_fill_7));
        colorList.add(mContext.getResources().getColor(R.color.happy_color_fill_8));
        colorList.add(mContext.getResources().getColor(R.color.happy_color_fill_9));
        mColorList = colorList;
    }

    private void initHealthBtn(){
        //肾虚  气虚 阳虚  郁滞  血虚  痰湿 阴虚 脾虚 平和
        mHealthMap = new HashMap<>();
        mHealthMap.put("肾虚",R.drawable.shenxu_shouye_icon);
        mHealthMap.put("气虚",R.drawable.qixu_shouye_icon);
        mHealthMap.put("阳虚",R.drawable.yangxu_shouye_icon);
        mHealthMap.put("郁滞",R.drawable.yuzhi_shouye_icon);
        mHealthMap.put("痰湿",R.drawable.tanshi_shouye_icon);
        mHealthMap.put("阴虚",R.drawable.yinxu_shouye_icon);
        mHealthMap.put("脾虚",R.drawable.pixu_shouye_icon);
        mHealthMap.put("健康",100);
    }

    /**
     * 显示报告
     * @param reportInfo
     */
    private void resolveBackInfo(ReportInfo reportInfo){
        try {
            if (mReportInfo != null && Validator.isEffective(mReportInfo.shareUrl)) {
                Bitmap qrBitmap = ZXingUtils.createQRImage(mReportInfo.shareUrl, 100, 100);
                if (qrBitmap != null) {
                    img_report_share.setImageBitmap(qrBitmap);
                }
            }
            tv_report_check_time.setText("检测时间：" + reportInfo.displayTime);
            tv_report_health_result.setText(reportInfo.healthStatusText);
            if (reportInfo.healthScore == 100){
                reportInfo.healthScore = 99;//防止100的时候取不到对应的色值,报错
            }
            int healthCellCount = reportInfo.healthScore / 10;
            //此处动态添加亚健康下面的10个方格
            rl_health_container_bg.setBackgroundColor((int)mColorList.get(healthCellCount));//如果是20分,就去对应的色值
            addViews(healthCellCount);
            //此处动态添加健康状态的按钮,总共有九种,根据服务器返回进行显示
            addHealthViews();
            // 监测数值
            int faceL = (int) (reportInfo.faceScoreDetail.faceL * 1.0 / 255 * 100);
            mFaceLeftProgressBar.setProgress(faceL);
            int faceA = (int) (reportInfo.faceScoreDetail.faceA * 1.0 / 255 * 100);
            mFaceMiddleProgressBar.setProgress(faceA);
            int faceB = (int) (reportInfo.faceScoreDetail.faceB * 1.0 / 255 * 100);
            mFaceRightProgressBar.setProgress(faceB);
            int tongueL = (int) (reportInfo.tongueScoreDetail.tongueL * 1.0 / 255 * 100);
            mTongueLeftProgressBar.setProgress(tongueL);
            int tongueA = (int) (reportInfo.tongueScoreDetail.tongueA * 1.0 / 255 * 100);
            mTongueMiddleProgressBar.setProgress(tongueA);
            int tongueB = (int) (reportInfo.tongueScoreDetail.tongueB * 1.0 / 255 * 100);
            mTongueRightProgressBar.setProgress(tongueB);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addViews(int count){

        if (mlLReport_color_container != null) {
            mlLReport_color_container.removeAllViews();
        }
        //此处添加颜色充满的方格
        for (int i = 0; i < count; i++) {
            View view = View.inflate(this, R.layout.happy_report_fill_layout, null);
            View colorView = view.findViewById(R.id.report_fill_bg);
            colorView.setBackgroundColor((int)mColorList.get(i));
            //view.setLayoutParams(new LinearLayout.LayoutParams(1 * wWidth / 3, ViewGroup.LayoutParams.WRAP_CONTENT));
            view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            mlLReport_color_container.addView(view);
        }

        //添加无填充颜色的方格
        if (count < 10){
            for (int j = 0; j < 10 - count; j++){
                View view = View.inflate(this, R.layout.happy_report_not_fill_layout, null);
                view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                mlLReport_color_container.addView(view);
            }
        }

    }

    private void addHealthViews(){
        if (mlL_health_state_container != null) {
            mlL_health_state_container.removeAllViews();
        }
        List symptomList = mReportInfo.symptomList;
        //显示最少一个,最多三个,这边直接用button,图片有点问题,直接用布局
        if (symptomList != null && symptomList.size() > 0){
            for (int i = 0; i < symptomList.size(); i++) {
                ReportInfo.Symptom symItem = (ReportInfo.Symptom) symptomList.get(i);
                View view = View.inflate(this, R.layout.report_health_btn_layout, null);
                LinearLayout lL_health_container = (LinearLayout) view.findViewById(R.id.lL_health_container);
                TextView tvTitle = (TextView) view.findViewById(R.id.tv_health_title); //img_health
                ImageView imgHealth = (ImageView) view.findViewById(R.id.img_health);
                view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                mlL_health_state_container.addView(view);
                tvTitle.setText(symItem.name);
                if (symItem.name.equals("健康")){
                    imgHealth.setVisibility(View.GONE);
                }else {
                    //此处背景资源放到Map里面,根据服务器返回字段,去map中取值,最后如果是平和的话,则隐藏其中的图片 gone
                    imgHealth.setVisibility(View.VISIBLE);
                    imgHealth.setBackgroundResource((int)mHealthMap.get(symItem.name));
                }

                //点击健康状况弹框,如果是健康,则不弹框 也没有对应的symptomDefinitions
                if (!symItem.name.equals("健康")){
                    final ReportInfo.SymptomDefinition definitionItem = (ReportInfo.SymptomDefinition) mReportInfo.solutions.symptomDefinitions.get(i);
                    lL_health_container.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            HealthStateDialog stateDialog = new HealthStateDialog(mContext,R.style.dialog,definitionItem);
                            stateDialog.show();
                        }
                    });
                }

            }
        }
    }


    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final HappyReportActivity activity = (HappyReportActivity) mActivityReference.get();
                if (activity != null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:   //显示对话框
                            if (activity.mProgressDialog != null) {
                                activity.mProgressDialog.setMessage("正在获取报告...");
                                activity.mProgressDialog.show();
                            }
                            break;
                        case MessageType.CLOSE_DIALOG:  //关闭对话框
                            if (activity.mProgressDialog != null) {
                                activity.mProgressDialog.dismiss();
                            }
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成
                            if (msg.arg1 == DataType.GET_REPORT_BY_ID) {
                                SparseArray<Object> result = (SparseArray<Object>) msg.obj;
                                String errno = (String) result.get(0);
                                if ("0".equals(errno)) {
                                   ReportInfo reportInfo = (ReportInfo) result.get(1);
                                   if (reportInfo != null) {
                                       activity.mReportInfo = reportInfo;
                                       activity.resolveBackInfo(reportInfo);
                                   }
                                } else if ("1".equals(errno)){
                                    String errMsg = (String) result.get(1);
                                    T.shortToast(activity, errMsg);
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                MyLogger.e(TAG, "handleMessage Exception!e:" + e.getMessage());
            }
        }
    }

}
